package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Override
    @Transactional
    public void submit(Orders orders) {
        //1. 数据准备
        Long currentId = BaseContext.getCurrentId();//当前登陆用户id
        //1.1 购物车数据
        LambdaQueryWrapper<ShoppingCart> scLqw = new LambdaQueryWrapper<>();
        scLqw.eq(ShoppingCart::getUserId, currentId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(scLqw);
        if (shoppingCartList == null || shoppingCartList.size() <= 0) {
            throw new CustomException("购物车数据为空，无法下单");
        }
        //1.2 地址簿数据
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null) {
            throw new CustomException("地址为空");
        }
        //1.3 用户数据
        User user = userService.getById(currentId);
        if (user == null) {
            throw new CustomException("用户为空");
        }

        //1.4 封装为List<OrderDetail> 集合
        long orderId = IdWorker.getId(); //生成订单Id

        //总金额
        AtomicInteger totalAmount = new AtomicInteger(0);

        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            BeanUtils.copyProperties(shoppingCart, orderDetail);

            //计算当前商品的小计
            BigDecimal amount = shoppingCart.getAmount();//单价
            Integer number = shoppingCart.getNumber();//数量
            //单价x数量
            BigDecimal multiply = amount.multiply(new BigDecimal(number));//小计
            //把小计累加到总金额上
            totalAmount.getAndAdd(multiply.intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //1.5 封装为Orders实体类
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));
        orders.setAmount(new BigDecimal(totalAmount.get()));
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserName(user.getName());
        orders.setPhone(addressBook.getPhone());
        orders.setUserId(currentId);
        orders.setStatus(2);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));


        //2. 保存数据到订单表
        save(orders);
        //3. 保存数据（集合）到订单明细表
        orderDetailService.saveBatch(orderDetailList);
        //4. 清空购物车
        shoppingCartService.remove(scLqw);
    }

    @Override
    public Page<OrdersDto> listByPageAndCondition(int page, int pageSize) {
        // 先分页查出Orders
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        page(pageInfo, lqw);
        // 得到全部订单数据
        List<Orders> records = pageInfo.getRecords();
        // 遍历订单数据 得到OrdersDto集合
        List<OrdersDto> collect = records.stream().map(o -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(o, ordersDto);
            // 通过当前订单项的id得到ordersDetail集合
            Long id = o.getId();
            LambdaQueryWrapper<OrderDetail> odsLqw = new LambdaQueryWrapper<>();
            odsLqw.eq(OrderDetail::getOrderId, id);
            List<OrderDetail> list = orderDetailService.list(odsLqw);
            // 将得到的OrdersDetail集合赋值到每一个ordersDto的集合中
            ordersDto.setOrderDetails(list);
            return ordersDto;
        }).collect(Collectors.toList());
        Page<OrdersDto> listPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, listPage);
        listPage.setRecords(collect);
        return listPage;
    }

    @Override
    public Page<OrdersDto> pageByCondition(Integer page, Integer pageSize, Long number, LocalDateTime beginTime, LocalDateTime endTime) {
        // 先分页查出Order
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.like(number != null, Orders::getNumber, number);
        lqw.between(beginTime != null && endTime != null, Orders::getCheckoutTime, beginTime, endTime);
        page(ordersPage, lqw);
        List<Orders> records = ordersPage.getRecords();
        // 此时拿到的records就是订单项
        List<OrdersDto> collect = records.stream().map(r -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(r, ordersDto);
            // 根据订单中的地址id查到详细地址信息
            LambdaQueryWrapper<AddressBook> absLqw = new LambdaQueryWrapper<>();
            absLqw.eq(AddressBook::getId, r.getAddressBookId());
            String detail = addressBookService.getOne(absLqw).getDetail();
            ordersDto.setAddress(detail);
            return ordersDto;
        }).collect(Collectors.toList());
        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage, ordersDtoPage);
        ordersDtoPage.setRecords(collect);
        return ordersDtoPage;
    }
}